Merge "Remove usages of deprecated User::getRights."
[lhc/web/wiklou.git] / includes / block / BlockManager.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Block;
22
23 use DateTime;
24 use DateTimeZone;
25 use DeferredUpdates;
26 use IP;
27 use MediaWiki\Config\ServiceOptions;
28 use MediaWiki\Permissions\PermissionManager;
29 use MediaWiki\User\UserIdentity;
30 use MWCryptHash;
31 use User;
32 use WebRequest;
33 use WebResponse;
34 use Wikimedia\IPSet;
35
36 /**
37 * A service class for checking blocks.
38 * To obtain an instance, use MediaWikiServices::getInstance()->getBlockManager().
39 *
40 * @since 1.34 Refactored from User and Block.
41 */
42 class BlockManager {
43 // TODO: This should be UserIdentity instead of User
44 /** @var User */
45 private $currentUser;
46
47 /** @var WebRequest */
48 private $currentRequest;
49
50 /** @var PermissionManager */
51 private $permissionManager;
52
53 /**
54 * TODO Make this a const when HHVM support is dropped (T192166)
55 *
56 * @var array
57 * @since 1.34
58 */
59 public static $constructorOptions = [
60 'ApplyIpBlocksToXff',
61 'CookieSetOnAutoblock',
62 'CookieSetOnIpBlock',
63 'DnsBlacklistUrls',
64 'EnableDnsBlacklist',
65 'ProxyList',
66 'ProxyWhitelist',
67 'SecretKey',
68 'SoftBlockRanges',
69 ];
70
71 /**
72 * @param ServiceOptions $options
73 * @param User $currentUser
74 * @param WebRequest $currentRequest
75 * @param PermissionManager $permissionManager
76 */
77 public function __construct(
78 ServiceOptions $options,
79 User $currentUser,
80 WebRequest $currentRequest,
81 PermissionManager $permissionManager
82 ) {
83 $options->assertRequiredOptions( self::$constructorOptions );
84 $this->options = $options;
85 $this->currentUser = $currentUser;
86 $this->currentRequest = $currentRequest;
87 $this->permissionManager = $permissionManager;
88 }
89
90 /**
91 * Get the blocks that apply to a user. If there is only one, return that, otherwise
92 * return a composite block that combines the strictest features of the applicable
93 * blocks.
94 *
95 * TODO: $user should be UserIdentity instead of User
96 *
97 * @internal This should only be called by User::getBlockedStatus
98 * @param User $user
99 * @param bool $fromReplica Whether to check the replica DB first.
100 * To improve performance, non-critical checks are done against replica DBs.
101 * Check when actually saving should be done against master.
102 * @return AbstractBlock|null The most relevant block, or null if there is no block.
103 */
104 public function getUserBlock( User $user, $fromReplica ) {
105 $isAnon = $user->getId() === 0;
106
107 // TODO: If $user is the current user, we should use the current request. Otherwise,
108 // we should not look for XFF or cookie blocks.
109 $request = $user->getRequest();
110
111 # We only need to worry about passing the IP address to the block generator if the
112 # user is not immune to autoblocks/hardblocks, and they are the current user so we
113 # know which IP address they're actually coming from
114 $ip = null;
115 $sessionUser = $this->currentUser;
116 // the session user is set up towards the end of Setup.php. Until then,
117 // assume it's a logged-out user.
118 $globalUserName = $sessionUser->isSafeToLoad()
119 ? $sessionUser->getName()
120 : IP::sanitizeIP( $this->currentRequest->getIP() );
121 if ( $user->getName() === $globalUserName &&
122 !$this->permissionManager->userHasRight( $user, 'ipblock-exempt' ) ) {
123 $ip = $this->currentRequest->getIP();
124 }
125
126 // User/IP blocking
127 // After this, $blocks is an array of blocks or an empty array
128 // TODO: remove dependency on DatabaseBlock
129 $blocks = DatabaseBlock::newListFromTarget( $user, $ip, !$fromReplica );
130
131 // Cookie blocking
132 $cookieBlock = $this->getBlockFromCookieValue( $user, $request );
133 if ( $cookieBlock instanceof AbstractBlock ) {
134 $blocks[] = $cookieBlock;
135 }
136
137 // Proxy blocking
138 if ( $ip !== null && !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) ) {
139 // Local list
140 if ( $this->isLocallyBlockedProxy( $ip ) ) {
141 $blocks[] = new SystemBlock( [
142 'byText' => wfMessage( 'proxyblocker' )->text(),
143 'reason' => wfMessage( 'proxyblockreason' )->plain(),
144 'address' => $ip,
145 'systemBlock' => 'proxy',
146 ] );
147 } elseif ( $isAnon && $this->isDnsBlacklisted( $ip ) ) {
148 $blocks[] = new SystemBlock( [
149 'byText' => wfMessage( 'sorbs' )->text(),
150 'reason' => wfMessage( 'sorbsreason' )->plain(),
151 'address' => $ip,
152 'systemBlock' => 'dnsbl',
153 ] );
154 }
155 }
156
157 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
158 if ( $this->options->get( 'ApplyIpBlocksToXff' )
159 && $ip !== null
160 && !in_array( $ip, $this->options->get( 'ProxyWhitelist' ) )
161 ) {
162 $xff = $request->getHeader( 'X-Forwarded-For' );
163 $xff = array_map( 'trim', explode( ',', $xff ) );
164 $xff = array_diff( $xff, [ $ip ] );
165 // TODO: remove dependency on DatabaseBlock
166 $xffblocks = DatabaseBlock::getBlocksForIPList( $xff, $isAnon, !$fromReplica );
167 $blocks = array_merge( $blocks, $xffblocks );
168 }
169
170 // Soft blocking
171 if ( $ip !== null
172 && $isAnon
173 && IP::isInRanges( $ip, $this->options->get( 'SoftBlockRanges' ) )
174 ) {
175 $blocks[] = new SystemBlock( [
176 'address' => $ip,
177 'byText' => 'MediaWiki default',
178 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
179 'anonOnly' => true,
180 'systemBlock' => 'wgSoftBlockRanges',
181 ] );
182 }
183
184 // Filter out any duplicated blocks, e.g. from the cookie
185 $blocks = $this->getUniqueBlocks( $blocks );
186
187 if ( count( $blocks ) > 0 ) {
188 if ( count( $blocks ) === 1 ) {
189 $block = $blocks[ 0 ];
190 } else {
191 $block = new CompositeBlock( [
192 'address' => $ip,
193 'byText' => 'MediaWiki default',
194 'reason' => wfMessage( 'blockedtext-composite-reason' )->plain(),
195 'originalBlocks' => $blocks,
196 ] );
197 }
198 return $block;
199 }
200
201 return null;
202 }
203
204 /**
205 * Given a list of blocks, return a list of unique blocks.
206 *
207 * This usually means that each block has a unique ID. For a block with ID null,
208 * if it's an autoblock, it will be filtered out if the parent block is present;
209 * if not, it is assumed to be a unique system block, and kept.
210 *
211 * @param AbstractBlock[] $blocks
212 * @return AbstractBlock[]
213 */
214 private function getUniqueBlocks( array $blocks ) {
215 $systemBlocks = [];
216 $databaseBlocks = [];
217
218 foreach ( $blocks as $block ) {
219 if ( $block instanceof SystemBlock ) {
220 $systemBlocks[] = $block;
221 } elseif ( $block->getType() === DatabaseBlock::TYPE_AUTO ) {
222 if ( !isset( $databaseBlocks[$block->getParentBlockId()] ) ) {
223 $databaseBlocks[$block->getParentBlockId()] = $block;
224 }
225 } else {
226 $databaseBlocks[$block->getId()] = $block;
227 }
228 }
229
230 return array_merge( $systemBlocks, $databaseBlocks );
231 }
232
233 /**
234 * Try to load a block from an ID given in a cookie value. If the block is invalid
235 * doesn't exist, or the cookie value is malformed, remove the cookie.
236 *
237 * @param UserIdentity $user
238 * @param WebRequest $request
239 * @return DatabaseBlock|bool The block object, or false if none could be loaded.
240 */
241 private function getBlockFromCookieValue(
242 UserIdentity $user,
243 WebRequest $request
244 ) {
245 $cookieValue = $request->getCookie( 'BlockID' );
246 if ( is_null( $cookieValue ) ) {
247 return false;
248 }
249
250 $blockCookieId = $this->getIdFromCookieValue( $cookieValue );
251 if ( !is_null( $blockCookieId ) ) {
252 // TODO: remove dependency on DatabaseBlock
253 $block = DatabaseBlock::newFromID( $blockCookieId );
254 if (
255 $block instanceof DatabaseBlock &&
256 $this->shouldApplyCookieBlock( $block, $user->isAnon() )
257 ) {
258 return $block;
259 }
260 }
261
262 $this->clearBlockCookie( $request->response() );
263
264 return false;
265 }
266
267 /**
268 * Check if the block loaded from the cookie should be applied.
269 *
270 * @param DatabaseBlock $block
271 * @param bool $isAnon The user is logged out
272 * @return bool The block sould be applied
273 */
274 private function shouldApplyCookieBlock( DatabaseBlock $block, $isAnon ) {
275 if ( !$block->isExpired() ) {
276 switch ( $block->getType() ) {
277 case DatabaseBlock::TYPE_IP:
278 case DatabaseBlock::TYPE_RANGE:
279 // If block is type IP or IP range, load only
280 // if user is not logged in (T152462)
281 return $isAnon &&
282 $this->options->get( 'CookieSetOnIpBlock' );
283 case DatabaseBlock::TYPE_USER:
284 return $block->isAutoblocking() &&
285 $this->options->get( 'CookieSetOnAutoblock' );
286 default:
287 return false;
288 }
289 }
290 return false;
291 }
292
293 /**
294 * Check if an IP address is in the local proxy list
295 *
296 * @param string $ip
297 * @return bool
298 */
299 private function isLocallyBlockedProxy( $ip ) {
300 $proxyList = $this->options->get( 'ProxyList' );
301 if ( !$proxyList ) {
302 return false;
303 }
304
305 if ( !is_array( $proxyList ) ) {
306 // Load values from the specified file
307 $proxyList = array_map( 'trim', file( $proxyList ) );
308 }
309
310 $proxyListIPSet = new IPSet( $proxyList );
311 return $proxyListIPSet->match( $ip );
312 }
313
314 /**
315 * Whether the given IP is in a DNS blacklist.
316 *
317 * @param string $ip IP to check
318 * @param bool $checkWhitelist Whether to check the whitelist first
319 * @return bool True if blacklisted.
320 */
321 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
322 if ( !$this->options->get( 'EnableDnsBlacklist' ) ||
323 ( $checkWhitelist && in_array( $ip, $this->options->get( 'ProxyWhitelist' ) ) )
324 ) {
325 return false;
326 }
327
328 return $this->inDnsBlacklist( $ip, $this->options->get( 'DnsBlacklistUrls' ) );
329 }
330
331 /**
332 * Whether the given IP is in a given DNS blacklist.
333 *
334 * @param string $ip IP to check
335 * @param array $bases Array of Strings: URL of the DNS blacklist
336 * @return bool True if blacklisted.
337 */
338 private function inDnsBlacklist( $ip, array $bases ) {
339 $found = false;
340 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
341 if ( IP::isIPv4( $ip ) ) {
342 // Reverse IP, T23255
343 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
344
345 foreach ( $bases as $base ) {
346 // Make hostname
347 // If we have an access key, use that too (ProjectHoneypot, etc.)
348 $basename = $base;
349 if ( is_array( $base ) ) {
350 if ( count( $base ) >= 2 ) {
351 // Access key is 1, base URL is 0
352 $hostname = "{$base[1]}.$ipReversed.{$base[0]}";
353 } else {
354 $hostname = "$ipReversed.{$base[0]}";
355 }
356 $basename = $base[0];
357 } else {
358 $hostname = "$ipReversed.$base";
359 }
360
361 // Send query
362 $ipList = $this->checkHost( $hostname );
363
364 if ( $ipList ) {
365 wfDebugLog(
366 'dnsblacklist',
367 "Hostname $hostname is {$ipList[0]}, it's a proxy says $basename!"
368 );
369 $found = true;
370 break;
371 }
372
373 wfDebugLog( 'dnsblacklist', "Requested $hostname, not found in $basename." );
374 }
375 }
376
377 return $found;
378 }
379
380 /**
381 * Wrapper for mocking in tests.
382 *
383 * @param string $hostname DNSBL query
384 * @return string[]|bool IPv4 array, or false if the IP is not blacklisted
385 */
386 protected function checkHost( $hostname ) {
387 return gethostbynamel( $hostname );
388 }
389
390 /**
391 * Set the 'BlockID' cookie depending on block type and user authentication status.
392 *
393 * @since 1.34
394 * @param User $user
395 */
396 public function trackBlockWithCookie( User $user ) {
397 $request = $user->getRequest();
398 if ( $request->getCookie( 'BlockID' ) !== null ) {
399 // User already has a block cookie
400 return;
401 }
402
403 // Defer checks until the user has been fully loaded to avoid circular dependency
404 // of User on itself (T180050 and T226777)
405 DeferredUpdates::addCallableUpdate(
406 function () use ( $user, $request ) {
407 $block = $user->getBlock();
408 $response = $request->response();
409 $isAnon = $user->isAnon();
410
411 if ( $block ) {
412 if ( $block instanceof CompositeBlock ) {
413 // TODO: Improve on simply tracking the first trackable block (T225654)
414 foreach ( $block->getOriginalBlocks() as $originalBlock ) {
415 if ( $this->shouldTrackBlockWithCookie( $originalBlock, $isAnon ) ) {
416 $this->setBlockCookie( $originalBlock, $response );
417 return;
418 }
419 }
420 } else {
421 if ( $this->shouldTrackBlockWithCookie( $block, $isAnon ) ) {
422 $this->setBlockCookie( $block, $response );
423 }
424 }
425 }
426 },
427 DeferredUpdates::PRESEND
428 );
429 }
430
431 /**
432 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
433 * the same as the block's, to a maximum of 24 hours.
434 *
435 * @since 1.34
436 * @internal Should be private.
437 * Left public for backwards compatibility, until DatabaseBlock::setCookie is removed.
438 * @param DatabaseBlock $block
439 * @param WebResponse $response The response on which to set the cookie.
440 */
441 public function setBlockCookie( DatabaseBlock $block, WebResponse $response ) {
442 // Calculate the default expiry time.
443 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
444
445 // Use the block's expiry time only if it's less than the default.
446 $expiryTime = $block->getExpiry();
447 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
448 $expiryTime = $maxExpiryTime;
449 }
450
451 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
452 $expiryValue = DateTime::createFromFormat(
453 'YmdHis',
454 $expiryTime,
455 new DateTimeZone( 'UTC' )
456 )->format( 'U' );
457 $cookieOptions = [ 'httpOnly' => false ];
458 $cookieValue = $this->getCookieValue( $block );
459 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
460 }
461
462 /**
463 * Check if the block should be tracked with a cookie.
464 *
465 * @param AbstractBlock $block
466 * @param bool $isAnon The user is logged out
467 * @return bool The block sould be tracked with a cookie
468 */
469 private function shouldTrackBlockWithCookie( AbstractBlock $block, $isAnon ) {
470 if ( $block instanceof DatabaseBlock ) {
471 switch ( $block->getType() ) {
472 case DatabaseBlock::TYPE_IP:
473 case DatabaseBlock::TYPE_RANGE:
474 return $isAnon && $this->options->get( 'CookieSetOnIpBlock' );
475 case DatabaseBlock::TYPE_USER:
476 return !$isAnon &&
477 $this->options->get( 'CookieSetOnAutoblock' ) &&
478 $block->isAutoblocking();
479 default:
480 return false;
481 }
482 }
483 return false;
484 }
485
486 /**
487 * Unset the 'BlockID' cookie.
488 *
489 * @since 1.34
490 * @param WebResponse $response
491 */
492 public static function clearBlockCookie( WebResponse $response ) {
493 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
494 }
495
496 /**
497 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
498 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
499 *
500 * @since 1.34
501 * @internal Should be private.
502 * Left public for backwards compatibility, until DatabaseBlock::getIdFromCookieValue is removed.
503 * @param string $cookieValue The string in which to find the ID.
504 * @return int|null The block ID, or null if the HMAC is present and invalid.
505 */
506 public function getIdFromCookieValue( $cookieValue ) {
507 // The cookie value must start with a number
508 if ( !is_numeric( substr( $cookieValue, 0, 1 ) ) ) {
509 return null;
510 }
511
512 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
513 $bangPos = strpos( $cookieValue, '!' );
514 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
515 if ( !$this->options->get( 'SecretKey' ) ) {
516 // If there's no secret key, just use the ID as given.
517 return $id;
518 }
519 $storedHmac = substr( $cookieValue, $bangPos + 1 );
520 $calculatedHmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
521 if ( $calculatedHmac === $storedHmac ) {
522 return $id;
523 } else {
524 return null;
525 }
526 }
527
528 /**
529 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
530 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
531 * be the block ID.
532 *
533 * @since 1.34
534 * @internal Should be private.
535 * Left public for backwards compatibility, until DatabaseBlock::getCookieValue is removed.
536 * @param DatabaseBlock $block
537 * @return string The block ID, probably concatenated with "!" and the HMAC.
538 */
539 public function getCookieValue( DatabaseBlock $block ) {
540 $id = $block->getId();
541 if ( !$this->options->get( 'SecretKey' ) ) {
542 // If there's no secret key, don't append a HMAC.
543 return $id;
544 }
545 $hmac = MWCryptHash::hmac( $id, $this->options->get( 'SecretKey' ), false );
546 $cookieValue = $id . '!' . $hmac;
547 return $cookieValue;
548 }
549
550 }